import json

from django.http import JsonResponse
from interview.models import User


# 客户端分数上传接口
def upload(request):
    # 获取数据
    data = json.loads(request.body)
    name = data.get('name')
    score = data.get('score')
    # 数据校验
    if name is None or score is None:
        return JsonResponse({'message': '数据异常'})
    if len(name) > 255:
        return JsonResponse({'message': '客户端号超长'})
    if score <= 0 or score >= 10000000:
        return JsonResponse({'message': '分数错误'})
    # 储存数据
    User.objects.update_or_create(name=name, defaults={'name': name, 'score': score})
    return JsonResponse({'message': '上传成功'})


# 客户端查询排名接口
def query(request):
    # 获取数据
    data = json.loads(request.body)
    name = data.get('name')
    start = data.get('start')
    end = data.get('end')
    # 数据校验
    if name is None or start is None or end is None:
        return JsonResponse({'message': '数据异常'})
    if start > end:
        return JsonResponse({'message': '排名不对'})
    # 获取客户号数据
    try:
        user_name = User.objects.get(name=name)
    except:
        return JsonResponse({'message': '客户号不存在'})

    # 获取排名数据
    users = User.objects.all().order_by('-score')[start - 1:end]
    # 处理排名数据
    result = []
    for i, v in enumerate(users):
        result.append({'ranking': start + i, 'name': v.name, 'score': v.score})
    # 获取客户号排名
    count = User.objects.filter(score__gte=user_name.score).count()
    # 判断排名
    if start >= count or count >= end:
        result.append({'ranking': count, 'name': user_name.name, 'score': user_name.score})
    return JsonResponse({'message': '查询成功', 'result': result})
